/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.quician.webapp.controllers;

import com.quician.fifa.Usuario;
import com.quician.webapp.ejbs.UserManager;
import com.quician.webapp.filters.SecurityFilter;
import java.io.IOException;
import java.io.Serializable;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.enterprise.context.RequestScoped;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Named;
import javax.servlet.http.HttpSession;

/**
 *
 * @author quician
 */
@Named(value="LoginController")
@RequestScoped
public class LoginController implements Serializable{
    private static final long serialVersionUID = 1L;

    private String User;
    private String Password;
    
    @EJB
    private UserManager userManager;
    
    public void Login(){
        
        try {
            Usuario user = userManager.verificarLogin(User, Password);
            FacesContext fctx = FacesContext.getCurrentInstance();
            
            if(user == null){
                fctx.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,"Error","User or Password Incorrect."));
            }
            else{
                HttpSession session = (HttpSession)fctx.getExternalContext().getSession(true);
                session.setAttribute(SecurityFilter.LOGGED_USER, user.getUsername());
                session.setAttribute(SecurityFilter.IS_LOGGED_IN, Boolean.TRUE);
                fctx.getExternalContext().redirect("/WebApp/Private/equipos/Equipos.xhtml");
                //fctx.getExternalContext().redirect("/WebApp/Private/Main.xhtml");
            }
            
        } catch (IOException ex) {
            Logger.getLogger(LoginController.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    public void LogOut(){
        try {
            FacesContext ctx = FacesContext.getCurrentInstance();
            HttpSession session = (HttpSession)ctx.getExternalContext().getSession(false);
            session.invalidate();
            ctx.getExternalContext().redirect("/WebApp/Private/login.xhtml");
        } catch (IOException ex) {
            Logger.getLogger(LoginController.class.getName()).log(Level.SEVERE, null, ex);
        }
        
    }
    
    public String getUser() {return User;}
    public String getPassword() {return Password;}
    public void setUser(String User) {this.User = User;}
    public void setPassword(String Password) {this.Password = Password;}
    
}
